package com.jy.wms.service;


import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.jy.wms.common.RedisUtils;
import com.jy.wms.common.SetStatus;
import com.jy.wms.common.UUIDUtils;
import com.jy.wms.common.annotions.BaseServiceDescribe;
import com.jy.wms.common.base.BaseService;
import com.jy.wms.common.base.DictionaryInfo;
import com.jy.wms.common.base.ServiceException;
import com.jy.wms.common.base.SucessException;
import com.jy.wms.common.mapUtils;
import com.jy.wms.common.result.TreeResult;
import com.jy.wms.dao.*;
import com.jy.wms.pojo.*;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;

/**
    * @ClassName: WmsOwnerService.java
    * @Description: TODO(这里用一句话描述这个类的作用)
    * @Author liyi
    * @Date Wed Sep 06 16:26:01 CST 2017
    */

    @Service
    public class WmsOwnerService extends BaseService<WmsOwnerMapper,WmsOwner> {

    @Autowired
    protected WmsLibraryPositionMapper wmsLibraryPositionMapper;
    @Autowired
    private WmsLibraryAreaMapper wmsLibraryAreaMapper;
    @Autowired
    private WmsTurnoverRuleMiddleMapper wmsTurnoverRuleMiddleMapper;
    @Autowired
    private WmsOwnerOrdertypeMapper wmsOwnerOrdertypeMapper;
    @Autowired
    private WmsOwnerReceiptorderconfigMapper wmsOwnerReceiptorderconfigMapper;
    @Autowired
    private WmsOwnerShipmentorderconfigMapper wmsOwnerShipmentorderconfigMapper;
    @Autowired
    private SysDictionaryService sysDictionaryService;
    @Autowired
    RedisUtils redisUtils;




    /**
     * 查询空闲库位树
     * @return List<TreeResult>
     * @throws ServiceException
     */
    @BaseServiceDescribe(moduleName = "货主管理",btnName = "查询空闲库位树")
    public List<TreeResult> getLibraryareaTree(String ckid) throws Exception {
        try {
            //所属库区不重复的dis
            Set<String> sskqids = new HashSet<String>();
            List<WmsLibraryPosition> list = wmsLibraryPositionMapper.selectPostion(ckid);
            for (WmsLibraryPosition wmsLibraryPosition : list) {
                sskqids.add(wmsLibraryPosition.getSskqid());
            }
            List<TreeResult> wmsLibraryAreaTreeList = new ArrayList<TreeResult>();
            if(sskqids.size()>0){
                List<WmsLibraryArea> wmsLibraryAreaList = wmsLibraryAreaMapper.baseSelectBathPrimaryKeys(new ArrayList<String>(sskqids));
                for (WmsLibraryArea wmsLibraryArea : wmsLibraryAreaList) {
                    TreeResult treeResult = new TreeResult();
                    treeResult.setKey(wmsLibraryArea.getId());
                    treeResult.setLabel(wmsLibraryArea.getMc());
                    List<TreeResult> childrenList = new ArrayList<TreeResult>();
                    for (WmsLibraryPosition wmsLibraryPosition : list) {
                        if(wmsLibraryPosition.getSskqid().equals(wmsLibraryArea.getId())){
                            TreeResult children = new TreeResult();
                            children.setKey(wmsLibraryPosition.getId());
                            children.setLabel(wmsLibraryPosition.getMc());
                            childrenList.add(children);
                        }
                    }
                    treeResult.setChildren(childrenList);
                    wmsLibraryAreaTreeList.add(treeResult);
                }
            }
            return wmsLibraryAreaTreeList;
        } catch (Exception e) {
            throw new ServiceException("查询空闲库位树",e);
        }
    }

    /**
     * 查询货主拥有库位
     * @param sshzid 所属货主ID
     * @return List<TreeResult>
     * @throws ServiceException
     */
    @BaseServiceDescribe(moduleName = "货主管理",btnName = "查询货主拥有库位")
    public List<TreeResult> getLibraryareaTreeOwn(String sshzid) throws Exception{
        //所属库区不重复的dis
        List<TreeResult> wmsLibraryAreaTreeList =  new ArrayList<TreeResult>();
        try {
            Set<String> sskqids = new HashSet<String>();
            List<WmsLibraryPosition> list = wmsLibraryPositionMapper.selectPostionBySshzid(sshzid);
            for (WmsLibraryPosition wmsLibraryPosition : list) {
                sskqids.add(wmsLibraryPosition.getSskqid());
            }
            if(sskqids.size()>0){
                List<WmsLibraryArea> wmsLibraryAreaList = wmsLibraryAreaMapper.baseSelectBathPrimaryKeys(new ArrayList<String>(sskqids));
                for (WmsLibraryArea wmsLibraryArea : wmsLibraryAreaList) {
                    TreeResult treeResult = new TreeResult();
                    treeResult.setKey(wmsLibraryArea.getId());
                    treeResult.setLabel(wmsLibraryArea.getMc());
                    List<TreeResult> childrenList = new ArrayList<TreeResult>();
                    for (WmsLibraryPosition wmsLibraryPosition : list) {
                        if(wmsLibraryPosition.getSskqid().equals(wmsLibraryArea.getId())){
                            TreeResult children = new TreeResult();
                            children.setKey(wmsLibraryPosition.getId());
                            children.setLabel(wmsLibraryPosition.getMc());
                            childrenList.add(children);
                        }
                    }
                    treeResult.setChildren(childrenList);
                    wmsLibraryAreaTreeList.add(treeResult);
                }
            }
            return  wmsLibraryAreaTreeList;
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("查询货主拥有库位",e);
        }
    }

    /**
     * 查询货主拥有库位
     * @param mc 仓库名称
     * @return List<Integer>
     * @throws ServiceException
     */
    @BaseServiceDescribe(moduleName = "货主管理",btnName = "根据货主名称查询对应的库位Ids")
    public List<Integer> getAllByMc(String mc)throws Exception{
        try {
            return dao.getAllByMc(mc);
        } catch (Exception e) {
            throw new ServiceException("查询货主拥及空闲的库位",e);
        }
    }

    /**
     * 查询货主拥及空闲的库位
     * @param sshzid 所属货主ID
     * @return JSONObject
     * @throws Exception
     */
    @BaseServiceDescribe(moduleName = "货主管理",btnName = "查询货主拥及空闲的库位")
    public JSONObject selectPostionBySshzidOrFree(String sshzid,String ckid) throws Exception{
        JSONObject json = new JSONObject();
        try {
            //所属库区不重复的dis
            Set<String> sskqids = new HashSet<String>();
            List<String> ids = new ArrayList<String>();
            List<WmsLibraryPosition> list = wmsLibraryPositionMapper.selectPostionBySshzidOrFree(sshzid,ckid);
            for (WmsLibraryPosition wmsLibraryPosition : list) {
                sskqids.add(wmsLibraryPosition.getSskqid());
                if(!(wmsLibraryPosition.getSshzid().equals("0"))){
                    ids.add(wmsLibraryPosition.getId());
                }
            }
            List<TreeResult> wmsLibraryAreaTreeList = new ArrayList<TreeResult>();
            if(sskqids.size()>0){
                List<WmsLibraryArea> wmsLibraryAreaList = wmsLibraryAreaMapper.baseSelectBathPrimaryKeys(new ArrayList<String>(sskqids));
                for (WmsLibraryArea wmsLibraryArea : wmsLibraryAreaList) {
                    TreeResult treeResult = new TreeResult();
                    treeResult.setKey(wmsLibraryArea.getId());
                    treeResult.setLabel(wmsLibraryArea.getMc());
                    List<TreeResult> childrenList = new ArrayList<TreeResult>();
                    for (WmsLibraryPosition wmsLibraryPosition : list) {
                        if(wmsLibraryPosition.getSskqid().equals(wmsLibraryArea.getId())){
                            TreeResult children = new TreeResult();
                            children.setKey(wmsLibraryPosition.getId());
                            children.setLabel(wmsLibraryPosition.getMc());
                            childrenList.add(children);
                        }
                    }
                    treeResult.setChildren(childrenList);
                    wmsLibraryAreaTreeList.add(treeResult);
                }
            }
            json.put("data",wmsLibraryAreaTreeList);
            json.put("ids",ids);
            return json;
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("查询货主拥及空闲的库位",e);
        }
    }

    /**
     * 新增货主信息 同时保存货主、预收货单、预发货单、货主用户中间表
     * @param entity 货主实体类
     * @return WmsOwner
     */
    @BaseServiceDescribe(moduleName = "货主管理",btnName = "新增货主信息")
    @Transactional
    public void insertByOwmer(WmsOwner entity,String ckid)throws ServiceException, SucessException {
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("mc",entity.getMc());
        map.put("ckid",ckid);
        Integer count = dao.getCountByMc(map);
        //判断货主名称是否重复
        if(count == 0){
            //进行周转规则保存
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String date = sdf.format(new Date());
            String zzgzIds [] = entity.getZzgzIds().split(",");
            List<WmsTurnoverRuleMiddle> list = new ArrayList<WmsTurnoverRuleMiddle>();
            WmsTurnoverRuleMiddle wmsTurnoverRuleMiddle = null;
            for(int i = 0; i < zzgzIds.length; i++){
                wmsTurnoverRuleMiddle = new WmsTurnoverRuleMiddle();
                wmsTurnoverRuleMiddle.setId(UUIDUtils.uuid());
                wmsTurnoverRuleMiddle.setSshzid(entity.getId());
                wmsTurnoverRuleMiddle.setZzgzid(zzgzIds[i]);
                wmsTurnoverRuleMiddle.setPx(String.valueOf(i+1));
                list.add(wmsTurnoverRuleMiddle);
            }
            Integer flag =  wmsTurnoverRuleMiddleMapper.baseInsertBathPrimaryKeys(list);
            //保存选中库位的集合
            if(entity.getLibrarypositionIds().size()>0){
                wmsLibraryPositionMapper.baseUpdateByPrimaryKeys(entity.getLibrarypositionIds(),entity.getId());
            }
            entity.setGxsj(new Date());
            //保存货主预收货单导入配置表
//            WmsOwnerReceiptorderconfig wmsOwnerReceiptorderconfig = new WmsOwnerReceiptorderconfig();
//            wmsOwnerReceiptorderconfig.setId(UUIDUtils.uuid());
//            wmsOwnerReceiptorderconfig.setCkid(ckid);
//            wmsOwnerReceiptorderconfig.setBth(entity.getReceiptorderconfig_bth());
//            wmsOwnerReceiptorderconfig.setBz(entity.getReceiptorderconfig_bz());
//            wmsOwnerReceiptorderconfig.setDdrq(entity.getReceiptorderconfig_ddrq());
//            wmsOwnerReceiptorderconfig.setDh(entity.getReceiptorderconfig_dh());
//            wmsOwnerReceiptorderconfig.setGxsj(date);
//            wmsOwnerReceiptorderconfig.setGys(entity.getReceiptorderconfig_gys());
//            wmsOwnerReceiptorderconfig.setHpbh(entity.getReceiptorderconfig_hpbh());
//            wmsOwnerReceiptorderconfig.setHpdwmc(entity.getReceiptorderconfig_hpdwmc());
//            wmsOwnerReceiptorderconfig.setHppc(entity.getReceiptorderconfig_hppc());
//            wmsOwnerReceiptorderconfig.setHpscrq(entity.getReceiptorderconfig_hpscrq());
//            wmsOwnerReceiptorderconfig.setHpsl(entity.getReceiptorderconfig_hpsl());
//            wmsOwnerReceiptorderconfig.setLx(entity.getReceiptorderconfig_lx());
//            wmsOwnerReceiptorderconfig.setQzh(entity.getReceiptorderconfig_qzh());
//            wmsOwnerReceiptorderconfig.setSshzid(entity.getId());
//            wmsOwnerReceiptorderconfig.setYjdhrq(entity.getReceiptorderconfig_yjdhrq());
//            wmsOwnerReceiptorderconfigMapper.insert(wmsOwnerReceiptorderconfig);

            //保存货主发运订单导入配置表
//            WmsOwnerShipmentorderconfig wmsOwnerShipmentorderconfig = new WmsOwnerShipmentorderconfig();
//            wmsOwnerShipmentorderconfig.setId(UUIDUtils.uuid());
//            wmsOwnerShipmentorderconfig.setCkid(ckid);
//            wmsOwnerShipmentorderconfig.setGxsj(date);
//            wmsOwnerShipmentorderconfig.setBth(entity.getShipmentorderconfig_bth());
//            wmsOwnerShipmentorderconfig.setDdrq(entity.getShipmentorderconfig_ddrq());
//            wmsOwnerShipmentorderconfig.setDdsheng(entity.getShipmentorderconfig_ddsheng());
//            wmsOwnerShipmentorderconfig.setDdshi(entity.getShipmentorderconfig_ddshi());
//            wmsOwnerShipmentorderconfig.setDh(entity.getShipmentorderconfig_dh());
//            wmsOwnerShipmentorderconfig.setFhrq(entity.getShipmentorderconfig_fhrq());
//            wmsOwnerShipmentorderconfig.setGhdh(entity.getShipmentorderconfig_ghdh());
//            wmsOwnerShipmentorderconfig.setHpbh(entity.getShipmentorderconfig_hpbh());
//            wmsOwnerShipmentorderconfig.setHpdj(entity.getShipmentorderconfig_hpdj());
//            wmsOwnerShipmentorderconfig.setHpdwmc(entity.getShipmentorderconfig_hpdwmc());
//            wmsOwnerShipmentorderconfig.setHplsje(entity.getShipmentorderconfig_hplsje());
//            wmsOwnerShipmentorderconfig.setHpsl(entity.getShipmentorderconfig_hpsl());
//            wmsOwnerShipmentorderconfig.setKhbh(entity.getShipmentorderconfig_khbh());
//            wmsOwnerShipmentorderconfig.setKhmc(entity.getShipmentorderconfig_khmc());
//            wmsOwnerShipmentorderconfig.setLx(entity.getShipmentorderconfig_lx());
//            wmsOwnerShipmentorderconfig.setQzh(entity.getShipmentorderconfig_qzh());
//            wmsOwnerShipmentorderconfig.setShdz(entity.getShipmentorderconfig_shdz());
//            wmsOwnerShipmentorderconfig.setShr1(entity.getShipmentorderconfig_shr1());
//            wmsOwnerShipmentorderconfig.setShdz(entity.getShipmentorderconfig_shdz());
//            wmsOwnerShipmentorderconfig.setShr1dh(entity.getShipmentorderconfig_shr1dh());
//            wmsOwnerShipmentorderconfig.setShr2(entity.getShipmentorderconfig_shr2());
//            wmsOwnerShipmentorderconfig.setShr2dh(entity.getShipmentorderconfig_shr2dh());
//            wmsOwnerShipmentorderconfig.setSshzid(entity.getId());
//            wmsOwnerShipmentorderconfigMapper.insert(wmsOwnerShipmentorderconfig);
            Integer addCount = dao.insert(entity);
            if(addCount>0){
                throw new SucessException("新增货主成功");
            }else{
                throw new ServiceException("新增货主成功失败，未插入数据库");
            }
        }else{
            throw new ServiceException("货主名称重复");
        }
    }



    /**
     * 修改货主信息 同时修改货主、预收货单、预发货单
     * @param entity 货主实体类
     * @return WmsOwner
     */
    @BaseServiceDescribe(moduleName = "货主管理",btnName = "修改货主信息")
    @Transactional
    public void updateByOwmer(WmsOwner entity,String ckid)throws SucessException,ServiceException{
        Map<String,Object> map = new HashMap<String,Object>();
        //判断当前是否可以继续修改货主信息
        Boolean type = true;
        map.put("mc",entity.getMc());
        map.put("ckid",ckid);
        Integer count = dao.getCountByMc(map);
        //判断当前货主是否可以继续修改 如果名称不变则判断数据库是否有大于1的  如果名称改变判断数据库是否大于0
        WmsOwner wmsOwner = dao.selectById(entity.getId());
        if(wmsOwner.getMc().equals(entity.getMc()) && count > 1){
            type = false;
        }else if(!(wmsOwner.getMc().equals(entity.getMc())) && count > 0){
            type = false;
        }
        if(type){
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String date = sdf.format(new Date());
            //判断删除周转规则操作
            wmsTurnoverRuleMiddleMapper.baseDeleteByPrimaryKeyHzId(entity.getId());
            if(entity.getZzgzIds().length()>0){
                String zzgzIds[] = entity.getZzgzIds().split(",");
                //判断如果传入的周转规则ID为空的情况下
                List<WmsTurnoverRuleMiddle> list = new ArrayList<WmsTurnoverRuleMiddle>();
                WmsTurnoverRuleMiddle wmsTurnoverRuleMiddle = null;
                for (int i = 0; i < zzgzIds.length; i++) {
                    wmsTurnoverRuleMiddle = new WmsTurnoverRuleMiddle();
                    wmsTurnoverRuleMiddle.setId(UUIDUtils.uuid());
                    wmsTurnoverRuleMiddle.setSshzid(entity.getId());
                    wmsTurnoverRuleMiddle.setZzgzid(zzgzIds[i]);
                    wmsTurnoverRuleMiddle.setPx(String.valueOf(i + 1));
                    list.add(wmsTurnoverRuleMiddle);
                }
                wmsTurnoverRuleMiddleMapper.baseInsertBathPrimaryKeys(list);
            }
            //保存货主预收货单导入配置表
//            WmsOwnerReceiptorderconfig wmsOwnerReceiptorderconfig = new WmsOwnerReceiptorderconfig();
//            wmsOwnerReceiptorderconfig.setBth(entity.getReceiptorderconfig_bth());
//            wmsOwnerReceiptorderconfig.setBz(entity.getReceiptorderconfig_bz());
//            wmsOwnerReceiptorderconfig.setDdrq(entity.getReceiptorderconfig_ddrq());
//            wmsOwnerReceiptorderconfig.setDh(entity.getReceiptorderconfig_dh());
//            wmsOwnerReceiptorderconfig.setGxsj(date);
//            wmsOwnerReceiptorderconfig.setGys(entity.getReceiptorderconfig_gys());
//            wmsOwnerReceiptorderconfig.setHpbh(entity.getReceiptorderconfig_hpbh());
//            wmsOwnerReceiptorderconfig.setHpdwmc(entity.getReceiptorderconfig_hpdwmc());
//            wmsOwnerReceiptorderconfig.setHppc(entity.getReceiptorderconfig_hppc());
//            wmsOwnerReceiptorderconfig.setHpscrq(entity.getReceiptorderconfig_hpscrq());
//            wmsOwnerReceiptorderconfig.setHpsl(entity.getReceiptorderconfig_hpsl());
//            wmsOwnerReceiptorderconfig.setLx(entity.getReceiptorderconfig_lx());
//            wmsOwnerReceiptorderconfig.setQzh(entity.getReceiptorderconfig_qzh());
//            wmsOwnerReceiptorderconfig.setYjdhrq(entity.getReceiptorderconfig_yjdhrq());
//            wmsOwnerReceiptorderconfigMapper.baseUpdateByPrimaryKeySelectiveByHzid(wmsOwnerReceiptorderconfig);

            //保存货主发运订单导入配置表
//            WmsOwnerShipmentorderconfig wmsOwnerShipmentorderconfig = new WmsOwnerShipmentorderconfig();
//            wmsOwnerShipmentorderconfig.setGxsj(date);
//            wmsOwnerShipmentorderconfig.setBth(entity.getShipmentorderconfig_bth());
//            wmsOwnerShipmentorderconfig.setDdrq(entity.getShipmentorderconfig_ddrq());
//            wmsOwnerShipmentorderconfig.setDdsheng(entity.getShipmentorderconfig_ddsheng());
//            wmsOwnerShipmentorderconfig.setDdshi(entity.getShipmentorderconfig_ddshi());
//            wmsOwnerShipmentorderconfig.setDh(entity.getShipmentorderconfig_dh());
//            wmsOwnerShipmentorderconfig.setFhrq(entity.getShipmentorderconfig_fhrq());
//            wmsOwnerShipmentorderconfig.setGhdh(entity.getShipmentorderconfig_ghdh());
//            wmsOwnerShipmentorderconfig.setHpbh(entity.getShipmentorderconfig_hpbh());
//            wmsOwnerShipmentorderconfig.setHpdj(entity.getShipmentorderconfig_hpdj());
//            wmsOwnerShipmentorderconfig.setHpdwmc(entity.getShipmentorderconfig_hpdwmc());
//            wmsOwnerShipmentorderconfig.setHplsje(entity.getShipmentorderconfig_hplsje());
//            wmsOwnerShipmentorderconfig.setHpsl(entity.getShipmentorderconfig_hpsl());
//            wmsOwnerShipmentorderconfig.setKhbh(entity.getShipmentorderconfig_khbh());
//            wmsOwnerShipmentorderconfig.setKhmc(entity.getShipmentorderconfig_khmc());
//            wmsOwnerShipmentorderconfig.setLx(entity.getShipmentorderconfig_lx());
//            wmsOwnerShipmentorderconfig.setQzh(entity.getShipmentorderconfig_qzh());
//            wmsOwnerShipmentorderconfig.setShdz(entity.getShipmentorderconfig_shdz());
//            wmsOwnerShipmentorderconfig.setShr1(entity.getShipmentorderconfig_shr1());
//            wmsOwnerShipmentorderconfig.setShdz(entity.getShipmentorderconfig_shdz());
//            wmsOwnerShipmentorderconfig.setShr1dh(entity.getShipmentorderconfig_shr1dh());
//            wmsOwnerShipmentorderconfig.setShr2(entity.getShipmentorderconfig_shr2());
//            wmsOwnerShipmentorderconfig.setShr2dh(entity.getShipmentorderconfig_shr2dh());
//            wmsOwnerShipmentorderconfigMapper.baseUpdateByPrimaryKeySelectiveByHzid(wmsOwnerShipmentorderconfig);
            Integer updateConut = dao.baseUpdateByPrimaryKeySelective(entity);
            if(updateConut>0){
                throw new SucessException("修改货主信息成功");
            }else{
                throw new ServiceException("修改货主信息失败，未插入数据库");
            }
        }else{
            throw new ServiceException("货主名称重复");
        }
    }

    /**
     * 修改货主库位
     * @param map
     * @return WmsOwner
     */
    @BaseServiceDescribe(moduleName = "货主管理",btnName = "修改货主库位")
    public void editLibraryposition(Map<String,Object> map)throws SucessException,ServiceException {
        //用户选择修改后的库位IDS
        List<String> list = (List) JSONArray.fromObject(map.get("ids"));
        if(list.size() <= 0){
            throw new ServiceException("修改货主库位失败，请至少选择一个库位");
        }
        WmsOwner wmsOwner = dao.selectById(map.get("sshzid").toString());
        StringBuffer message = new StringBuffer();
        //判断出货主下没有选择 暂存库位 和 集货库位的情况
        if(!(wmsOwner.getDjcwid().equals("0")) || !(wmsOwner.getJhqkwid().equals("0"))){
            Boolean type = true;
            if(!(list.contains(wmsOwner.getDjcwid()))) {
                message.append("暂存库位 ");
                message.append(wmsLibraryPositionMapper.selectById(wmsOwner.getDjcwid()) == null ? "未选择，":wmsLibraryPositionMapper.selectById(wmsOwner.getDjcwid()).getMc()+" 未选择，");
                type = false;
            }
            if(!(list.contains(wmsOwner.getJhqkwid()))) {
                message.append("集货库位 ");
                message.append(wmsLibraryPositionMapper.selectById(wmsOwner.getJhqkwid()) == null ?"未选择，":wmsLibraryPositionMapper.selectById(wmsOwner.getJhqkwid()).getMc()+" 未选择，");
                type = false;
            }
            if(type){
                //请求货主下所拥有的库位后加入选择的库位
                dao.cleanLibrarypositionByHzid(map.get("sshzid").toString());
                Integer updateCount =  wmsLibraryPositionMapper.baseUpdateALLSshuid(list,map.get("sshzid").toString());
                if(updateCount>0){
                    throw new SucessException("修改货主库位成功");
                }else{
                    throw new ServiceException("修改货主库位失败，未插入数据库");
                }
            }else{
                message.append("修改失败");
                throw new ServiceException(message.toString());
            }
        }else {
            dao.cleanLibrarypositionByHzid(map.get("sshzid").toString());
            Integer updateCount =  wmsLibraryPositionMapper.baseUpdateALLSshuid(list,map.get("sshzid").toString());
            if(updateCount>0){
                throw new SucessException("修改货主库位成功");
            }else{
                throw new ServiceException("修改货主库位失败，未插入数据库");
            }
        }
    }

    /**
     * 修改货主订单类型
     * @param map
     * @return WmsOwner
     */
    @BaseServiceDescribe(moduleName = "货主管理",btnName = "修改货主订单类型")
    public void editOrderType(Map<String,Object> map)throws ServiceException,SucessException{
        List<String> list = (List) JSONArray.fromObject(map.get("ids"));
        wmsOwnerOrdertypeMapper.baseUpdateALLZero(map.get("sshzid").toString());
        if(list != null && list.size()>0){
            Integer updateCount =  wmsOwnerOrdertypeMapper.baseUpdateALLZdsh(list);
            if(updateCount>0){
                throw new SucessException("修改货主订单类型成功");
            }else{
                throw new ServiceException("修改货主订单类型失败，未插入数据库");
            }
        }
    }

    /**
     * 获取货主的订单类型列表（支持分页）
     * @param map
     * @param ckid 仓库ID
     * @return WmsOwner
     */
    @BaseServiceDescribe(moduleName = "货主管理",btnName = "获取货主的订单类型列表")
    public JSONObject getOrderTypeByHzId(Map<String,Object> map,String ckid)throws ServiceException{
        JSONObject json = new JSONObject();
        try {
            WmsOwnerOrdertype wmsOwnerOrdertype = (WmsOwnerOrdertype) mapUtils.mapToBean(map,WmsOwnerOrdertype.class);
            PageHelper.startPage(wmsOwnerOrdertype.getPage(),wmsOwnerOrdertype.getRows());
            wmsOwnerOrdertype.setCkid(ckid);
            Page<WmsOwnerOrdertype> list = (Page<WmsOwnerOrdertype>)wmsOwnerOrdertypeMapper.baseSelectPage(wmsOwnerOrdertype );
            for (WmsOwnerOrdertype type : list) {
                //获取否采集SN码值
                String value ="";
                value = sysDictionaryService.getTypeName(DictionaryInfo.wms_owner_ordertype_cjsn.toString(),type.getCjsn());
                type.setShow_cjsn(value);
                //获取分类的值
                value = sysDictionaryService.getTypeName(DictionaryInfo.wms_owner_ordertype_fl.toString(),type.getCjsn());
                type.setShow_fl(value);
            }
            json = SetStatus.setSearchType(JSONArray.fromObject(list).toString(),(int) list.getTotal());
            return json;
        } catch (Exception e) {
            throw new ServiceException("获取货主的订单类型列表失败",e);
        }
    }

    /**
     * 获取货主的订单类型所有选中的ids
     * @param sshzid 所属货主ID
     * @return WmsOwner
     */
    @BaseServiceDescribe(moduleName = "货主管理",btnName = "获取货主的订单类型所有选中的ids")
    public List<String> getOrderTypeIds(String sshzid)throws ServiceException{
        try {
            Map<String,Object> map = new HashMap<String,Object>();
            map.put("sshzid",sshzid);
            map.put("zdsh","1");
            return baseMapper.getOrderTypeIds(map);
        } catch (Exception e) {
            throw new ServiceException("获取货主的订单类型所有选中的ids",e);
        }
    }

    /**
     * 查询（根据货主名称模糊查询）
     * @param mc 货主名称
     * @return WmsOwner
     */
    @BaseServiceDescribe(moduleName = "货主管理",btnName = "根据货主名称模糊查询")
    public Page<WmsOwner> baseSelectByMc(String mc, int page, int rows,String ckid) throws ServiceException{
        try {
            PageHelper.startPage(page,rows);
            WmsOwner wmsOwner = new WmsOwner();
            wmsOwner.setMc(mc);
            wmsOwner.setCkid(ckid);
            Page<WmsOwner> list = (Page<WmsOwner>)dao.baseSelectByMc( wmsOwner );
            return list;
        } catch (Exception e) {
            throw new ServiceException("根据货主名称模糊查询货主列表",e);
        }
    }

     /**
     * 插入一条记录
     * @param entity 实体对象
     * @return int
     */
    public Integer baseInsert( WmsOwner entity ){
         return dao.baseInsert( entity );
    }

   /**
    * 插入一条记录（匹配有值的字段）
    * @param entity 实体对象
    * @return int
    */
    public Integer baseInsertSelective( WmsOwner entity ){
         return dao.baseInsertSelective( entity );
    }

   /**
    * 删除（根据主键ID删除）
    * @param id 主键
    * @return int
    */
    public Integer baseDeleteByPrimaryKey( String id ){
         return dao.baseDeleteByPrimaryKey( id );
    }

   /**
    * 删除（根据ID 批量删除）
    * @param idList 主键ID列表
    * @return int
    */
    public Integer baseDeleteBathPrimaryKeys( List<String> idList ){
         return dao.baseDeleteBathPrimaryKeys( idList );
    }

    /**
    * 分页查询
    * @param entity 实体
    * @return Page<WmsOwner>
    */
    @BaseServiceDescribe(moduleName = "货主管理",btnName = "货主管理分页查询")
    public Page<WmsOwner> baseSelectPage(WmsOwner entity) throws ServiceException {
        try {
            PageHelper.startPage(entity.getPage(),entity.getRows());
            Page<WmsOwner> list = (Page<WmsOwner>)dao.baseSelectPage( entity);
            for (WmsOwner wmsOwner : list) {
                wmsOwner.setShow_djdps(redisUtils.selectByValue("wms_owner_djdps",wmsOwner.getDjdps()));
                wmsOwner.setShow_zxqx(redisUtils.selectByValue("wms_owner_zxqx",wmsOwner.getZxqx()));
                wmsOwner.setShow_slbuck(redisUtils.selectByValue("wms_owner_slbuck",wmsOwner.getSlbuck()));
                wmsOwner.setShow_dcfh(redisUtils.selectByValue("wms_owner_dcfh",wmsOwner.getDcfh()));
                wmsOwner.setShow_zyzdqr(redisUtils.selectByValue("wms_owner_zyzdqr",wmsOwner.getZyzdqr()));
                wmsOwner.setShow_bhzdqr(redisUtils.selectByValue("wms_owner_bhzdqr",wmsOwner.getBhzdqr()));
                wmsOwner.setShow_shfk(redisUtils.selectByValue("wms_owner_shfk",wmsOwner.getShfk()));
                wmsOwner.setShow_shscpch(redisUtils.selectByValue("wms_owner_shscpch",wmsOwner.getShscpch()));
                wmsOwner.setShow_shscscrq(redisUtils.selectByValue("wms_owner_shscscrq",wmsOwner.getShscscrq()));
                wmsOwner.setShow_kcyj(redisUtils.selectByValue("wms_owner_kcyj",wmsOwner.getKcyj()));
                wmsOwner.setShow_pdwwcqx(redisUtils.selectByValue("wms_owner_pdwwcqx",wmsOwner.getPdwwcqx()));
                wmsOwner.setShow_djpda(redisUtils.selectByValue("wms_owner_djpda",wmsOwner.getDjpda()));
                wmsOwner.setShow_sfbh(redisUtils.selectByValue("wms_owner_sfbh",wmsOwner.getSfbh()));
                wmsOwner.setShow_zjfs(redisUtils.selectByValue("wms_owner_zjfs",wmsOwner.getZjfs()));
                wmsOwner.setShow_yxj(redisUtils.selectByValue("wms_owner_yxj",wmsOwner.getYxj()));
                wmsOwner.setShow_dps(redisUtils.selectByValue("wms_owner_dps",wmsOwner.getDps()));
                wmsOwner.setShow_ckfh(redisUtils.selectByValue("wms_owner_ckfh",wmsOwner.getCkfh()));
                wmsOwner.setShow_cz(redisUtils.selectByValue("wms_owner_cz",wmsOwner.getCz()));
                wmsOwner.setShow_fhdymd(redisUtils.selectByValue("wms_owner_fhdymd",wmsOwner.getFhdymd()));
                wmsOwner.setShow_zcd(redisUtils.selectByValue("wms_owner_zcd",wmsOwner.getZcd()));
                wmsOwner.setShow_cmhpm(redisUtils.selectByValue("wms_owner_cmhpm",wmsOwner.getCmhpm()));
                wmsOwner.setShow_smLpn(redisUtils.selectByValue("wms_owner_smLpn",wmsOwner.getSmLpn()));
            }
            return list;
        } catch (Exception e) {
            throw new ServiceException("分页查询货主信息失败",e);
        }
    }

    @BaseServiceDescribe(moduleName = "货主管理",btnName = "根据货主Id查询货主的周转规则ids")
    public List<String> getZzgzByHzid(String sshzid) throws ServiceException{
        try {
            List<String> ids = dao.getZzgzByHzid(sshzid);
            return ids;
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("根据货主Id查询货主的周转规则ids失败",e);
        }
    }

   /**
    * 查询（根据主键ID查询）
    * @param id 主键ID
    * @return WmsOwner
    */
   @BaseServiceDescribe(moduleName = "货主管理",btnName = "根据ID查询货主信息")
    public WmsOwner baseSelectByPrimaryKey( String id )throws ServiceException{
        WmsOwner wmsOwner = null;
        try {
            return wmsOwner = dao.baseSelectByPrimaryKey( id );
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("查询唯一货主信息失败",e);
        }
    }

   /**
    * 查询（根据ID 批量查询）
    * @param idList 主键ID列表
    * @return list
    */
    public Integer baseSelectBathPrimaryKeys( List<WmsOwner> idList ){
         return dao.baseSelectBathPrimaryKeys( idList );
    }

   /**
    *修改 （匹配有值的字段）
    * @param entity 主键ID列表
    * @return int
    */
   @BaseServiceDescribe(moduleName = "货主管理",btnName = "修改货主信息")
   public Integer baseUpdateByPrimaryKeySelective( WmsOwner entity)throws ServiceException,SucessException{
       Integer updateCount = dao.baseUpdateByPrimaryKeySelective( entity );
       if(updateCount>0){
           throw new SucessException("修改货主信息成功");
       }else{
           throw new ServiceException("修改货主信息失败,未插入数据库");
       }
   }

   /**
    *修改（根据主键ID修改）
    * @param entity 主键ID列表
    * @return int
    */
    public Integer baseUpdateByPrimaryKey( WmsOwner entity ){
         return dao.baseUpdateByPrimaryKey( entity );
    }

    /**
     * 查询货主拥有待检库位
     * @param sshzid 所属货主ID
     * @param lx 类型
     * @return
     */
    @BaseServiceDescribe(moduleName = "货主管理",btnName = "查询货主拥有待检库位")
    public List<TreeResult> getDetectionBySshzid( String sshzid,String lx )throws ServiceException{
        List<TreeResult> wmsLibraryAreaTreeList = null;
        try {
            List<WmsLibraryPosition> list = wmsLibraryPositionMapper.getDetectionBySshzid(sshzid,lx);
            Set<String> sskqids = new HashSet<String>();
            for (WmsLibraryPosition wmsLibraryPosition : list) {
                sskqids.add(wmsLibraryPosition.getSskqid());
            }
            wmsLibraryAreaTreeList = new ArrayList<TreeResult>();
            if(sskqids.size()>0){
                List<WmsLibraryArea> wmsLibraryAreaList = wmsLibraryAreaMapper.baseSelectBathPrimaryKeys(new ArrayList<String>(sskqids));
                for (WmsLibraryArea wmsLibraryArea : wmsLibraryAreaList) {
                    TreeResult treeResult = new TreeResult();
                    treeResult.setKey(wmsLibraryArea.getId());
                    treeResult.setLabel(wmsLibraryArea.getMc());
                    List<TreeResult> childrenList = new ArrayList<TreeResult>();
                    for (WmsLibraryPosition wmsLibraryPosition : list) {
                        if(wmsLibraryPosition.getSskqid().equals(wmsLibraryArea.getId())){
                            TreeResult children = new TreeResult();
                            children.setKey(wmsLibraryPosition.getId());
                            children.setLabel(wmsLibraryPosition.getMc());
                            childrenList.add(children);
                        }
                    }
                    treeResult.setChildren(childrenList);
                    wmsLibraryAreaTreeList.add(treeResult);
                }
            }
        } catch (Exception e) {
            throw new ServiceException("查询货主拥有待检库位失败", e);
        }
        return  wmsLibraryAreaTreeList;
    }

    /**
     * 查询货主选中的待检库位
     * @param sshzid 所属货主ID
     * @return List<TreeResult>
     * @throws ServiceException
     */
    @BaseServiceDescribe(moduleName = "货主管理",btnName = "查询货主选中的待检库位")
    public List<TreeResult> getDetection(String sshzid) throws ServiceException {
        List<TreeResult> wmsLibraryAreaTreeList = new ArrayList<TreeResult>();;
        try {
            WmsOwner wmsOwner = dao.selectById(sshzid);
            //查询库位
            WmsLibraryPosition wmsLibraryPosition = wmsLibraryPositionMapper.baseSelectByPrimaryKey(wmsOwner.getDjcwid(), wmsOwner.getCkid(), null);
            if(wmsLibraryPosition != null){
                //查询库区
                WmsLibraryArea wmsLibraryArea = wmsLibraryAreaMapper.selectById(wmsLibraryPosition.getSskqid());
                if(wmsLibraryArea != null){
                    //加入库区
                    TreeResult treeResult = new TreeResult();
                    treeResult.setKey(wmsLibraryArea.getId());
                    treeResult.setLabel(wmsLibraryArea.getMc());
                    List<TreeResult> childrenList = new ArrayList<TreeResult>();
                    //加入库位
                    TreeResult children = new TreeResult();
                    children.setKey(wmsLibraryPosition.getId());
                    children.setLabel(wmsLibraryPosition.getMc());
                    childrenList.add(children);
                    treeResult.setChildren(childrenList);
                    wmsLibraryAreaTreeList.add(treeResult);
                }
            }
            return wmsLibraryAreaTreeList;
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("查询货主拥有库位失败", e);
        }
    }

    /**
     * 查询货主选中的待检库位
     * @param sshzid 所属货主ID
     * @return List<TreeResult>
     * @throws ServiceException
     */
    @BaseServiceDescribe(moduleName = "货主管理",btnName = "查询货主选中的理货库位")
    public List<TreeResult> getJhqkw(String sshzid) throws ServiceException {
        List<TreeResult> wmsLibraryAreaTreeList = new ArrayList<TreeResult>();;
        try {
            WmsOwner wmsOwner = dao.selectById(sshzid);
            //查询库位
            WmsLibraryPosition wmsLibraryPosition = wmsLibraryPositionMapper.baseSelectByPrimaryKey(wmsOwner.getJhqkwid(), wmsOwner.getCkid(), null);
            if(wmsLibraryPosition != null){
                //查询库区
                WmsLibraryArea wmsLibraryArea = wmsLibraryAreaMapper.selectById(wmsLibraryPosition.getSskqid());
                if(wmsLibraryArea != null){
                    //加入库区
                    TreeResult treeResult = new TreeResult();
                    treeResult.setKey(wmsLibraryArea.getId());
                    treeResult.setLabel(wmsLibraryArea.getMc());
                    List<TreeResult> childrenList = new ArrayList<TreeResult>();
                    //加入库位
                    TreeResult children = new TreeResult();
                    children.setKey(wmsLibraryPosition.getId());
                    children.setLabel(wmsLibraryPosition.getMc());
                    childrenList.add(children);
                    treeResult.setChildren(childrenList);
                    wmsLibraryAreaTreeList.add(treeResult);
                }
            }
            return wmsLibraryAreaTreeList;
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("查询货主拥有库位失败", e);
        }
    }

    @BaseServiceDescribe(moduleName = "货主管理",btnName = "查询货主拥有的暂存库位、集货库位")
    public JSONObject getAllKw(String sshzid) throws ServiceException{
        try {
            return JSONObject.fromObject(dao.getAllKw(sshzid));
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("查询货主拥有的暂存库位、集货库位失败");
        }
    }

    @BaseServiceDescribe(moduleName = "货主管理",btnName = "保存货主的集货库位 及 暂存库位")
    public void addAllKw(Map<String,Object> map) throws ServiceException,SucessException{
        Map<String,Object> param = new HashMap<String,Object>();
        WmsOwner wmsOwner = new WmsOwner();
        //集货库位名称
        String jhqkwMc = map.get("jhqkwMc").toString();
        //暂存库位名称
        String djcwMc = map.get("djcwMc").toString();
        String sshzid = map.get("id").toString();
        //进行保存集货库位操作
        param.put("sshzid",sshzid);
        param.put("mc",jhqkwMc);
        param.put("lx","5");
        String kwid = dao.getKwByMc(param);
        //清空map数据 后面保存使用
        map.clear();
        map.put("id",sshzid);
        if(kwid != null){
            //保存集货库位
            map.put("jhqkwid",kwid);
        }else{
            map.put("jhqkwid",null);
        }
        //进行保存暂存库位操作
        param.put("mc",djcwMc);
        param.put("lx","4");
        kwid = dao.getKwByMc(param);
        if(kwid != null){
            //保存暂存库位
            map.put("djcwid",kwid);
        }else{
            map.put("djcwid",null);
        }
        if(map.get("djcwid")==null && map.get("jhqkwid")==null){
            throw new ServiceException("保存集货库位，暂存库位失败");
        }else{
            Integer integer = dao.baseUpdateByKw(map);
            if(map.get("djcwid")==null && map.get("jhqkwid")!=null && integer>0){
                throw new SucessException("保存集货库位成功，保存暂存库位失败");
            }else if(map.get("djcwid")!=null && map.get("jhqkwid")==null  && integer>0){
                throw new SucessException("保存暂存库位成功，保存集货库位失败");
            }else if(map.get("djcwid")!=null && map.get("jhqkwid")!=null && integer>0){
                throw new SucessException("保存成功");
            } else{
                throw new ServiceException("数据未插入数据库");
            }
        }
    }
}
